﻿using Admin.NET.Core.Service;
using Admin.NET.Application.Const;
using Admin.NET.Application.Entity;
using Microsoft.AspNetCore.Http;
using AngleSharp.Dom;
using Furion.DatabaseAccessor;
using System.Linq;
namespace Admin.NET.Application;
/// <summary>
/// 考试学科服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class KaoshiXuekeService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<KaoshiXueke> _rep;
    private readonly SqlSugarRepository<Kaoshi> _kaoshiRep;
    private readonly SqlSugarRepository<Xueke> _xuekeRep;
    public KaoshiXuekeService(SqlSugarRepository<KaoshiXueke> rep, SqlSugarRepository<Kaoshi> kaoshiRep, SqlSugarRepository<Xueke> xuekeRep)
    {
        _rep = rep;
        _kaoshiRep = kaoshiRep;
        _xuekeRep = xuekeRep;

    }

    /// <summary>
    /// 分页查询考试学科
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<KaoshiXuekeOutput>> Page(KaoshiXuekeInput input)
    {
        if(input.KaoshiId == null)
        {
            Oops.Oh("考试Id不能缺");
        }
        var query = _rep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.Beizhu.Contains(input.SearchKey.Trim())
            )
            .WhereIF(input.KaoshiId!=null, u => u.KaoshiId == input.KaoshiId)
            .WhereIF(input.XuekeId>0, u => u.XuekeId == input.XuekeId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Beizhu), u => u.Beizhu.Contains(input.Beizhu.Trim()))
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<Kaoshi>((u, kaoshiid) => u.KaoshiId == kaoshiid.Id )
            .LeftJoin<Xueke>((u, kaoshiid, xuekeid) => u.XuekeId == xuekeid.Id )
            .OrderBy(u => u.Index)
            .Select((u, kaoshiid, xuekeid) => new KaoshiXuekeOutput
            {
                Id = u.Id,
                KaoshiId = u.KaoshiId, 
                KaoshiIdName = kaoshiid.Name,
                XuekeId = u.XuekeId, 
                XuekeIdName = xuekeid.Name,
                StartShijian = u.StartShijian,
                EndShijian = u.EndShijian,
                Quanzhong = u.Quanzhong,
                Zongfen = u.Zongfen,
                Beizhu = u.Beizhu,
                CreateUserName = u.CreateUserName,
                UpdateUserName = u.UpdateUserName,
                Index = u.Index
            });
        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加考试学科
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task<long> Add(AddKaoshiXuekeInput input)
    {
        var entity = input.Adapt<KaoshiXueke>();
        var kaoshi = await _kaoshiRep.GetFirstAsync(u => u.Id == input.KaoshiId) ?? throw Oops.Oh("考试不存在");
        var xueke = await _xuekeRep.GetFirstAsync(u => u.Id == input.XuekeId) ?? throw Oops.Oh("学科不存在");
        await _rep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除考试学科
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(DeleteKaoshiXuekeInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        //await _rep.FakeDeleteAsync(entity);   //假删除
        await _rep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新考试学科
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(UpdateKaoshiXuekeInput input)
    {
        var entity = input.Adapt<KaoshiXueke>();
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 保存考试学科
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [UnitOfWork]
    [ApiDescriptionSettings(Name = "Save")]
    public async Task Save(SaveKaoshiXuekeInput input)
    {
        foreach (var item in input.data)
        {
            var kaoshi = await _kaoshiRep.GetFirstAsync(u => u.Id == item.KaoshiId) ?? throw Oops.Oh("考试不存在");
            var xueke = await _xuekeRep.GetFirstAsync(u => u.Id == item.XuekeId) ?? throw Oops.Oh("学科不存在");
            var entity = item.Adapt<KaoshiXueke>();
            await _rep.Context.Storageable(entity).ExecuteCommandAsync();
            //if (entity.Id == 0)
            //{
                
            //}
            //else
            //{
            //    await _rep.UpdateAsync(entity);
            //}
        }
        var list = await _rep.AsQueryable().Where(p => p.KaoshiId == input.KaoshiId).ToListAsync();
        foreach (var item in list)
        {
            if(input?.data?.FirstOrDefault(p=>p.KaoshiId == item.KaoshiId && p.XuekeId == item.XuekeId)== null)
            {
                await _rep.DeleteAsync(item);
            }
        }
    }

    /// <summary>
    /// 获取考试学科
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<KaoshiXueke> Detail([FromQuery] QueryByIdKaoshiXuekeInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取考试学科列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<KaoshiXuekeOutput>> List([FromQuery] KaoshiXuekeInput input)
    {
        return await _rep.AsQueryable().Select<KaoshiXuekeOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取考试列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "kaoshiKaoshiIdDropdown"), HttpGet]
    public async Task<dynamic> kaoshiKaoshiIdDropdown()
    {
        return await _rep.Context.Queryable<Kaoshi>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }
    /// <summary>
    /// 获取学科列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "XuekeXuekeIdDropdown"), HttpGet]
    public async Task<dynamic> XuekeXuekeIdDropdown()
    {
        return await _rep.Context.Queryable<Xueke>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }




}

